<template>
  <div class="students-container">
    <div class="page-header">
      <h2>学生管理</h2>
      <el-button v-if="userStore.isAdmin || userStore.isTeacher" type="primary" @click="handleAddStudent">
        <el-icon><Plus /></el-icon>添加学生
      </el-button>
    </div>

    <el-card class="box-card">
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="学号">
            <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="班级">
            <el-select v-model="searchForm.classId" placeholder="请选择班级" clearable>
              <el-option
                v-for="item in classList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="studentList" style="width: 100%" border>
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.gender === '男' ? 'primary' : 'success'">
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="className" label="班级" width="150" />
        <el-table-column prop="major" label="专业" width="150" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button v-if="userStore.isAdmin || userStore.isTeacher" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button v-if="userStore.isAdmin || userStore.isTeacher" size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
            <span v-if="userStore.isStudent">无操作权限</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑学生对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加学生' : '编辑学生'"
      width="50%"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="rules"
        label-width="80px"
        style="max-width: 600px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="studentForm.age" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="studentForm.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '../stores/user';

// 初始化用户存储
const userStore = useUserStore();

// 搜索表单
const searchForm = reactive({
  studentId: '',
  name: '',
  classId: '',
});

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 班级列表
const classList = ref([
  { value: '1', label: '计算机科学与技术1班' },
  { value: '2', label: '计算机科学与技术2班' },
  { value: '3', label: '软件工程1班' },
  { value: '4', label: '软件工程2班' },
  { value: '5', label: '人工智能1班' },
]);

// 学生列表
const studentList = ref([
  {
    id: 1,
    studentId: '2023001',
    name: '张三',
    gender: '男',
    age: 20,
    classId: '1',
    className: '计算机科学与技术1班',
    major: '计算机科学与技术',
    phone: '13800138001',
    email: 'zhangsan@example.com',
  },
  {
    id: 2,
    studentId: '2023002',
    name: '李四',
    gender: '女',
    age: 19,
    classId: '1',
    className: '计算机科学与技术1班',
    major: '计算机科学与技术',
    phone: '13800138002',
    email: 'lisi@example.com',
  },
  {
    id: 3,
    studentId: '2023003',
    name: '王五',
    gender: '男',
    age: 21,
    classId: '2',
    className: '计算机科学与技术2班',
    major: '计算机科学与技术',
    phone: '13800138003',
    email: 'wangwu@example.com',
  },
  {
    id: 4,
    studentId: '2023004',
    name: '赵六',
    gender: '女',
    age: 20,
    classId: '3',
    className: '软件工程1班',
    major: '软件工程',
    phone: '13800138004',
    email: 'zhaoliu@example.com',
  },
  {
    id: 5,
    studentId: '2023005',
    name: '钱七',
    gender: '男',
    age: 22,
    classId: '4',
    className: '软件工程2班',
    major: '软件工程',
    phone: '13800138005',
    email: 'qianqi@example.com',
  },
]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const studentFormRef = ref<FormInstance>();
const studentForm = reactive({
  id: 0,
  studentId: '',
  name: '',
  gender: '男',
  age: 18,
  classId: '',
  major: '',
  phone: '',
  email: '',
});

// 表单验证规则
const rules = reactive<FormRules>({
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
});

// 生命周期钩子
onMounted(() => {
  fetchStudentList();
});

// 获取学生列表
const fetchStudentList = () => {
  // 模拟后端接口请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 使用假数据
    total.value = studentList.value.length;
  }, 300);
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchStudentList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.studentId = '';
  searchForm.name = '';
  searchForm.classId = '';
  currentPage.value = 1;
  fetchStudentList();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchStudentList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchStudentList();
};

// 添加学生
const handleAddStudent = () => {
  dialogType.value = 'add';
  resetStudentForm();
  dialogVisible.value = true;
};

// 编辑学生
const handleEdit = (row: any) => {
  dialogType.value = 'edit';
  Object.assign(studentForm, row);
  dialogVisible.value = true;
};

// 删除学生
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该学生信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 模拟删除操作
      const index = studentList.value.findIndex((item) => item.id === row.id);
      if (index !== -1) {
        studentList.value.splice(index, 1);
        total.value -= 1;
        ElMessage.success('删除成功');
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 重置表单
const resetStudentForm = () => {
  studentForm.id = 0;
  studentForm.studentId = '';
  studentForm.name = '';
  studentForm.gender = '男';
  studentForm.age = 18;
  studentForm.classId = '';
  studentForm.major = '';
  studentForm.phone = '';
  studentForm.email = '';
};

// 提交表单
const submitForm = async () => {
  if (!studentFormRef.value) return;

  await studentFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 模拟添加操作
        const newStudent = {
          id: Date.now(),
          studentId: studentForm.studentId,
          name: studentForm.name,
          gender: studentForm.gender,
          age: studentForm.age,
          classId: studentForm.classId,
          className: classList.value.find((item) => item.value === studentForm.classId)?.label || '',
          major: studentForm.major,
          phone: studentForm.phone,
          email: studentForm.email,
        };
        studentList.value.push(newStudent);
        total.value += 1;
        ElMessage.success('添加成功');
      } else {
        // 模拟编辑操作
        const index = studentList.value.findIndex((item) => item.id === studentForm.id);
        if (index !== -1) {
          const updatedStudent = {
            ...studentList.value[index],
            studentId: studentForm.studentId,
            name: studentForm.name,
            gender: studentForm.gender,
            age: studentForm.age,
            classId: studentForm.classId,
            className: classList.value.find((item) => item.value === studentForm.classId)?.label || '',
            major: studentForm.major,
            phone: studentForm.phone,
            email: studentForm.email,
          };
          studentList.value[index] = updatedStudent;
          ElMessage.success('更新成功');
        }
      }
      dialogVisible.value = false;
    } else {
      console.log('验证失败', fields);
    }
  });
};
</script>

<style scoped>
.students-container {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>